import { message } from "@/utils/message";
import { computed } from "vue";
import { updateExhibitionStatus } from "@/api/exhibitionInfo";

// 需是hooks写法（函数中有return），避免失去响应性
export function useColumns(
  exhibitionList: any,
  handleViewCallback?: (row: any) => void,
  handleEditCallback?: (row: any) => void,
  handleRefreshCallback?: () => void
) {
  // 使用computed来保持响应性
  const tableData = computed(() => {
    return exhibitionList.value || [];
  });
  const columns: TableColumnList = [
    {
      label: "Logo",
      prop: "logo",
      width: 100,
      cellRenderer: ({ row }) => {
        // 使用新的OSS域名拼接
        const BASE_URL =
          "https://exhibition-bucket.oss-cn-beijing.aliyuncs.com";
        const logoUrl = row.logo
          ? `${BASE_URL}${row.logo}`
          : "/placeholder-logo.png";
        return (
          <img
            src={logoUrl}
            alt="Logo"
            style="width: 50px; height: 50px; object-fit: cover;"
          />
        );
      }
    },
    {
      label: "公司名称(中)",
      prop: "company_name_cn",
      width: 150,
      cellRenderer: ({ row }) => (
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          {{
            default: () => (
              <>
                <div>公司名称(中): {row.company_name_cn}</div>
              </>
            ),
            reference: () => <el-tag>{row.company_name_cn || "-"}</el-tag>
          }}
        </el-popover>
      )
    },
    {
      label: "公司名称(英)",
      prop: "company_name_en",
      width: 150,
      cellRenderer: ({ row }) => (
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          {{
            default: () => (
              <>
                <div>公司名称(英): {row.company_name_en}</div>
              </>
            ),
            reference: () => <el-tag>{row.company_name_en || "-"}</el-tag>
          }}
        </el-popover>
      )
    },
    {
      label: "地址(中)",
      prop: "addres_cn",
      width: 200,
      cellRenderer: ({ row }) => (
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          {{
            default: () => (
              <>
                <div>地址(中): {row.addres_cn}</div>
              </>
            ),
            reference: () => <el-tag>{row.addres_cn || "-"}</el-tag>
          }}
        </el-popover>
      )
    },
    {
      label: "地址(英)",
      prop: "addres_en",
      width: 200,
      cellRenderer: ({ row }) => (
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          {{
            default: () => (
              <>
                <div>地址(英): {row.addres_en}</div>
              </>
            ),
            reference: () => <el-tag>{row.addres_en || "-"}</el-tag>
          }}
        </el-popover>
      )
    },
    {
      label: "电话",
      prop: "telephone",
      width: 200
    },
    {
      label: "审批状态",
      prop: "status",
      width: 120,
      align: "center",
      cellRenderer: ({ row }) => {
        let statusText = "";
        let statusType = "";

        switch (row.status) {
          case 0:
            statusText = "审核中";
            statusType = "warning";
            break;
          case 1:
            statusText = "已通过";
            statusType = "success";
            break;
          case 2:
            statusText = "已退回";
            statusType = "danger";
            break;
          case 3:
            statusText = "待提交";
            statusType = "warning";
            break;
          default:
            statusText = "未知";
            statusType = "info";
        }

        return <el-tag type={statusType}>{statusText}</el-tag>;
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 220,
      cellRenderer: ({ row }) => (
        <>
          <el-button size="small" onClick={() => handleView(row)}>
            查看
          </el-button>
          <el-button size="small" onClick={() => handleEdit(row)}>
            修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            onClick={() => handleSubmit(row)}
          >
            提交审批
          </el-button>
        </>
      )
    }
  ];

  const handleView = row => {
    if (handleViewCallback) {
      handleViewCallback(row);
    } else {
      message(`您查看了第 ${row.id} 行，数据为：${JSON.stringify(row)}`, {
        type: "success"
      });
    }
  };

  const handleEdit = row => {
    // 统一拦截提示：0 审核中、1 已通过
    if (row.status === 0) {
      message("会刊正在审核中，不能修改", { type: "warning" });
      return;
    }
    if (row.status === 1) {
      message("会刊已通过，不能修改", { type: "warning" });
      return;
    }
    if (handleEditCallback) {
      handleEditCallback(row);
    } else {
      message(`您修改了第 ${row.id} 行，数据为：${JSON.stringify(row)}`, {
        type: "success"
      });
    }
  };

  const handleSubmit = async (row: any) => {
    // 状态：0=审核中，1=已通过，2=已退回，3=待提交
    if (row.status === 0) {
      message("已提交，不可重复审批", { type: "warning" });
      return;
    }
    if (row.status === 1) {
      message("已通过，不可重复审批", { type: "warning" });
      return;
    }
    if (row.status !== 2 && row.status !== 3) {
      message("只有已退回或待提交状态才能提交审批", { type: "warning" });
      return;
    }
    try {
      const result: any = await updateExhibitionStatus(
        row.id,
        row.exhibitor_id,
        0
      );
      if (result.code === 1) {
        message("提交审批成功", { type: "success" });
        // 刷新列表
        if (handleRefreshCallback) {
          handleRefreshCallback();
        }
      } else {
        message(result.msg || "提交审批失败", { type: "error" });
      }
    } catch (error) {
      console.error("提交审批失败:", error);
      message("提交审批失败", { type: "error" });
    }
  };

  return {
    columns,
    tableData
  };
}
